package com.fp.m7.client.widget;

import java.util.Iterator;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * A replacement for a horizontally-centered vertical panel which displays an EmptyListWidget when the contents are
 * empty.
 * 
 * @author 7
 */
public class VerticalPanelWithEmptyView extends Composite implements HasWidgets {

    private VerticalPanel panel;
    private VerticalPanel emptyVerticalPanel;
    private EmptyListWidget empty;
    private boolean isEmpty = true;

    public VerticalPanelWithEmptyView() {
        panel = new VerticalPanel();
        panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
        initWidget(panel);

        empty = new EmptyListWidget();
        panel.add(empty);

        emptyVerticalPanel = new VerticalPanel();
    }

    public HasText getEmptyLabel() {
        return empty.getLabel();
    }

    @Override
    public void add(Widget widget) {
        if (isEmpty) {
            panel.clear();
            isEmpty = false;
        }
        panel.add(widget);
    }

    @Override
    public void clear() {
        panel.clear();
        isEmpty = true;
        panel.add(empty);
    }

    @Override
    public Iterator<Widget> iterator() {
        return isEmpty ? emptyVerticalPanel.iterator() : panel.iterator();
    }

    @Override
    public boolean remove(Widget widget) {
        if (widget == empty) {
            return false;
        }

        boolean result = panel.remove(widget);
        if (panel.getWidgetCount() < 1) {
            panel.add(empty);
            isEmpty = true;
        }
        return result;
    }

}
